<template>
  <div>
    <el-card shadow="never">
      <div class="card-query">
        <div>
          <el-button
            icon="el-icon-document-add"
            type="primary"
            @click="handleAdd"
            >添加</el-button
          >
          <el-button
            icon="el-icon-refresh"
            type="primary"
            @click="handleRefresh"
            >刷新</el-button
          >
        </div>
      </div>
    </el-card>

    <el-table
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column label="#">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片">
        <template slot-scope="scope">
          <img :src="localhostPath + scope.row.paymentPicturePath" alt="" />
        </template>
      </el-table-column>
      <el-table-column label="支付方式">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.modeOfPayment }}</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="是否启用">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isEnable"
            @change="enblechange(scope.$index, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定删除吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button size="mini" type="danger" slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加框 -->
    <el-dialog title="支付设置" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="支付方式"
          :label-width="formLabelWidth"
          prop="modeOfPayment"
        >
          <el-input v-model="form.modeOfPayment" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            :class="{ hide: hideUpload }"
            ref="upload"
            action="#"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            list-type="picture-card"
            :limit="1"
            :auto-upload="false"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :file-list="listarr"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <my-cropper
            ref="myCropper"
            @getFile="getFile"
            @upAgain="upAgain"
          ></my-cropper>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyCropper from "../../components/cropper.vue";
import {
  addPayment,
  getPayment,
  enablePayment,
  deletePayment,
  editPayment
} from "../../api/pay";
import common from "../../utils/common";

export default {
  components: { MyCropper },

  data() {
    return {
      localhostPath: common.localhostPath,
      dialogFormVisible: false,
      formLabelWidth: "100px",
      form: {
        id: 0,
        modeOfPayment: "",
      },
      rules: {
        modeOfPayment: [
          { required: true, message: "请输入支付名称", trigger: "blur" },
        ],
      },
      // 当上传一张图片后隐藏上传框
      hideUpload: false,
      // 放图片的数组
      listarr: [],
      tableData: [],
    };
  },
  mounted() {
    getPayment().then(({ data }) => {
      this.tableData = data.data;
    });
  },
  methods: {
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.form.modeOfPayment = row.modeOfPayment;
      this.form.id = row.id;
      this.newIndex = index;
      this.hideUpload = false;
    },
    handleDelete(index, row) {
      deletePayment(row.id).then(({ data }) => {
        this.tableData.splice(index, 1);
        this.$message.success(data.msg);
      });
    },
    //刷新
    handleRefresh() {
      location.reload();
    },
    // 添加
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
      this.listarr = [];
      this.hideUpload = false;
    },
    //上传
    handleRemove() {
      this.hideUpload = false;
    },
    handleBeforeUpload(file) {
      console.log("before");
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "警告",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
      }
      let size = file.size / 1024 / 1024 / 2;
      if (size > 2) {
        this.$notify.warning({
          title: "警告",
          message: "图片大小必须小于2M",
        });
      }
    },
    handleChange(file) {
      this.hideUpload = true;
      this.dialogImageUrl = file.url;
      // if (fileList.length > 0) {
      //   this.photoList = [fileList[fileList.length - 1]];
      // }
      this.handleCrop(file);
    },
    //上传图片触发
    handleCrop(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.open(file.raw || file, 100, 100, 1, 1);
      });
    },
    // 点击弹框重新时触发
    upAgain() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    // 获取裁剪后的图片
    getFile(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.close();
      });
      var url = window.URL.createObjectURL(file);
      this.listarr.push({ name: file.name, url: url, file: file });
    },
    //确定上传支付信息(支付方式和图片)
    confirm(formName) {
      if (this.form.id == undefined) {
        // 添加
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.listarr.length == 0) {
              this.$message.error("支付图片不能为空");
            } else {
              const fileObj = this.listarr[0].file;
              const form1 = new FormData();
              form1.append("imageFile", fileObj);
              form1.append("modeOfPayment", this.form.modeOfPayment);

              addPayment(form1).then(({ data }) => {
                if (data.code == 200) {
                  this.tableData.push(data.data);
                  this.dialogFormVisible = false;
                  this.$refs.upload.clearFiles();
                } else {
                  this.$message.error(data.msg);
                }
              });
            }
          } else {
            this.$message.error("该空不能为空，请填写完毕重新提交");
          }
        });
      } else {
        //编辑
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.listarr.length == 0) {
              this.$message.error("支付图片不能为空");
            } else {
              const fileObj = this.listarr[0].file;
              const form1 = new FormData();
              form1.append("imageFile", fileObj);
              form1.append("modeOfPayment", this.form.modeOfPayment);
              editPayment(this.form.id, form1).then(({ data }) => {
                this.tableData.splice(this.newIndex, 1, data.data);
                this.dialogFormVisible = false;
              });
              this.$refs.upload.clearFiles();
            }
          } else {
            this.$message.error("该空不能为空，请填写完毕重新提交");
          }
        });
      }
    },
    // 是否启用该支付方式
    enblechange(index, row) {
      enablePayment(row.id, row).then(({ data }) => {
        this.tableData.splice(index, data.data);
      });
    },
  },
};
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>